#include<bits/stdc++.h>
#define ll long long
using namespace std;
namespace IO
{
	char buff[1<<21],*p1=buff,*p2=buff;
	char getch(){return p1==p2&&(p2=((p1=buff)+fread(buff,1,1<<21,stdin)),p1==p2)?EOF:*p1++;}
	template<typename T>void read(T &x){char ch=getch();int fl=1;x=0;while(ch>'9'||ch<'0'){if(ch=='-')fl=-1;ch=getch();}while(ch<='9'&&ch>='0'){x=x*10+ch-48;ch=getch();}x*=fl;}
	template<typename T>void read_s(T &x){char ch=getch();while(ch<'a'||ch>'z')ch=getch();while(ch>='a'&&ch<='z'){x+=ch;ch=getch();}}
	template<typename T,typename ...Args>void read(T &x,Args& ...args){read(x);read(args...);}
	char obuf[1<<21],*p3=obuf;
	void putch(char ch) {if(p3-obuf<(1<<21))*p3++=ch;else fwrite(obuf,p3-obuf,1,stdout),p3=obuf,*p3++=ch;}
	char ch[100];
	template<typename T>void write(T x) {if(!x)return putch('0');if(x<0)putch('-'),x*=-1;int top=0;while(x)ch[++top]=x%10+48,x/=10;while(top)putch(ch[top]),top--;}
	template<typename T,typename ...Args>void write(T x,Args ...args) {write(x);write(args...);}
	void put(string s){for(int i=0;i<s.size();i++)putch(s[i]);}
	void flush(){fwrite(obuf,p3-obuf,1,stdout);}
}
using namespace IO;
int t,n,mod;
int a[1005][1005],b[1005][1005],c[1005][1005];
int p[1005];
int tmpa[1005],tmpb[1005],tmpc[1005];
inline int Mod(int x){return x>=mod?x-=mod:x;}
signed main()
{
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	read(t);
	srand(time(NULL));
	while(t--)
	{
		read(mod,n);
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++) read(a[i][j]);
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++) read(b[i][j]);
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++) read(c[i][j]);
		int ans=1;
		for(int T=1;T<=20;T++)
		{
			if(!ans) break;
			memset(tmpa,0,sizeof tmpa);
			memset(tmpb,0,sizeof tmpb);
			memset(tmpc,0,sizeof tmpc);
			for(int i=1;i<=n;i++) p[i]=rand();
			for(int j=1;j<=n;j++)
				for(int k=1;k<=n;k++)
					tmpa[j]=Mod(tmpa[j]+1ll*p[k]*a[k][j]%mod);
			for(int j=1;j<=n;j++)
				for(int k=1;k<=n;k++)
					tmpb[j]=Mod(tmpb[j]+1ll*tmpa[k]*b[k][j]%mod);
			for(int j=1;j<=n;j++)
				for(int k=1;k<=n;k++)
					tmpc[j]=Mod(tmpc[j]+1ll*p[k]*c[k][j]%mod);
			for(int i=1;i<=n;i++) if(tmpb[i]!=tmpc[i]) ans=0;
		}
		if(ans) puts("Yes");
		else puts("No");
	}
	flush();
	return 0;
}

